import baseApi from './baseApi';
import { getMerchantId } from './merchantService';

// 产品分类接口
export interface ProductCategory {
  id: number;
  name: string;
  status: number;
  sort?: number;
  parentId?: number;
  createdAt?: string;
  updatedAt?: string;
}

// 属性值接口
export interface AttributeValue {
  id: number;
  value: string;
}

// 商品属性接口
export interface ProductAttribute {
  id: number;
  name: string;
  type?: string;
  status?: number;
  attributeValues: AttributeValue[];
}

// 商品规格变体接口
export interface ProductVariant {
  id: number;
  attributeValues: AttributeValue[];
  code: string;
  price: number;
  stock: number;
  status: number;
}

// 产品接口
export interface Product {
  id: number;
  title: string;
  price: number;
  status: number;
  type: number;
  canBuy: boolean;
  category: ProductCategory;
  description: string;
  image: string;
  images?: string[];
  detail?: string;
  stock: number;
  sales: number;
  variants?: ProductVariant[];
  attributeGroups?: string[];
  attributesValue?: any[];
  createdAt: string;
  updatedAt: string;
}

// 分页请求参数
export interface PaginationParams {
  page?: number;
  pageSize?: number;
}

// 分页结果
export interface PaginationResult {
  total: number;
  page: number;
  pageSize: number;
}

// 商品列表响应
export interface ProductListResponse {
  pagination: PaginationResult;
  list: Product[];
}

// 商品分类列表响应
export interface CategoryListResponse {
  pagination: PaginationResult;
  list: ProductCategory[];
}

// 商品属性列表响应
export interface AttributeListResponse {
  pagination: PaginationResult;
  list: ProductAttribute[];
}

// 商品列表参数
export interface ProductListParams {
  page?: number;
  pageSize?: number;
  status?: number;
  categoryId?: number;
  category?: number;
  canBuy?: number;
  keyword?: string;
}

// 创建商品参数
export interface CreateProductParams {
  categoryId: number;
  type: number;
  canBuy: boolean;
  status: number;
  title: string;
  description: string;
  image: string;
  images?: string[];
  detail?: string;
  price: number;
  stock: number;
  attributesValue?: any[];
  variants?: any[];
}

// 创建分类参数
export interface CreateCategoryParams {
  name: string;
  status: number;
  sort?: number;
  parentId?: number;
}

// 创建属性参数
export interface CreateAttributeParams {
  name: string;
  status: number;
  type: string;
  attributeValues: { value: string }[];
  values?: { value: string }[];
}

// 响应接口类型
export interface ApiResponse<T> {
  code: number;
  message: string;
  data: T | null;
}

/**
 * 获取当前商户ID
 */
export const getMerchantInfo = async (): Promise<number> => {
  const merchantId = await getMerchantId();
  if (!merchantId) {
    throw new Error('未选择商户');
  }
  return merchantId;
};

// 商品服务
const productService = {
  /**
   * 获取商品列表
   */
  getProductList: async (params?: ProductListParams): Promise<ApiResponse<ProductListResponse>> => {
    try {
      const response = await baseApi.get('/admin/product/list', { params });
      return response.data;
    } catch (error) {
      return {
        code: -1,
        message: '获取商品列表失败',
        data: null
      };
    }
  },

  /**
   * 获取商品详情
   */
  getProductDetail: async (productId: number): Promise<ApiResponse<Product>> => {
    try {
      const response = await baseApi.get(`/admin/product/${productId}`);
      return response.data;
    } catch (error) {
      return {
        code: -1,
        message: '获取商品详情失败',
        data: null
      };
    }
  },

  /**
   * 创建商品
   */
  createProduct: async (params: CreateProductParams): Promise<ApiResponse<Product>> => {
    try {
      const response = await baseApi.post('/admin/product', params);
      return response.data;
    } catch (error) {
      return {
        code: -1,
        message: '创建商品失败',
        data: null
      };
    }
  },

  /**
   * 更新商品
   */
  updateProduct: async (productId: number, params: Partial<CreateProductParams>): Promise<ApiResponse<Product>> => {
    try {
      const response = await baseApi.put(`/admin/product/${productId}`, params);
      return response.data;
    } catch (error) {
      return {
        code: -1,
        message: '更新商品失败',
        data: null
      };
    }
  },

  /**
   * 删除商品
   */
  deleteProduct: async (productId: number): Promise<ApiResponse<any>> => {
    try {
      const response = await baseApi.delete(`/admin/product/${productId}`);
      return response.data;
    } catch (error) {
      return {
        code: -1,
        message: '删除商品失败',
        data: null
      };
    }
  },

  /**
   * 获取商品分类列表
   */
  getCategoryList: async (params?: PaginationParams): Promise<ApiResponse<CategoryListResponse>> => {
    try {
      const response = await baseApi.get('/admin/product/category/list', { params });
      return response.data;
    } catch (error) {
      return {
        code: -1,
        message: '获取商品分类列表失败',
        data: null
      };
    }
  },

  /**
   * 创建商品分类
   */
  createCategory: async (params: CreateCategoryParams): Promise<ApiResponse<ProductCategory>> => {
    try {
      const response = await baseApi.post('/admin/product/category', params);
      return response.data;
    } catch (error) {
      return {
        code: -1,
        message: '创建商品分类失败',
        data: null
      };
    }
  },

  /**
   * 更新商品分类
   */
  updateCategory: async (categoryId: number, params: Partial<CreateCategoryParams>): Promise<ApiResponse<ProductCategory>> => {
    try {
      const response = await baseApi.put(`/admin/product/category/${categoryId}`, params);
      return response.data;
    } catch (error) {
      return {
        code: -1,
        message: '更新商品分类失败',
        data: null
      };
    }
  },

  /**
   * 删除商品分类
   */
  deleteCategory: async (categoryId: number): Promise<ApiResponse<any>> => {
    try {
      const response = await baseApi.delete(`/admin/product/category/${categoryId}`);
      return response.data;
    } catch (error) {
      return {
        code: -1,
        message: '删除商品分类失败',
        data: null
      };
    }
  },

  /**
   * 获取商品属性列表
   */
  getAttributeList: async (params?: PaginationParams): Promise<ApiResponse<AttributeListResponse>> => {
    try {
      const response = await baseApi.get('/admin/product/attribute/list', { params });
      return response.data;
    } catch (error) {
      return {
        code: -1,
        message: '获取商品属性列表失败',
        data: null
      };
    }
  },

  /**
   * 创建商品属性
   */
  createAttribute: async (params: CreateAttributeParams): Promise<ApiResponse<ProductAttribute>> => {
    try {
      const response = await baseApi.post('/admin/product/attribute', params);
      return response.data;
    } catch (error) {
      return {
        code: -1,
        message: '创建商品属性失败',
        data: null
      };
    }
  },

  /**
   * 更新商品属性
   */
  updateAttribute: async (attributeId: number, params: Partial<CreateAttributeParams>): Promise<ApiResponse<ProductAttribute>> => {
    try {
      const response = await baseApi.put(`/admin/product/attribute/${attributeId}`, params);
      return response.data;
    } catch (error) {
      return {
        code: -1,
        message: '更新商品属性失败',
        data: null
      };
    }
  },

  /**
   * 删除商品属性
   */
  deleteAttribute: async (attributeId: number): Promise<ApiResponse<any>> => {
    try {
      const response = await baseApi.delete(`/admin/product/attribute/${attributeId}`);
      return response.data;
    } catch (error) {
      return {
        code: -1,
        message: '删除商品属性失败',
        data: null
      };
    }
  }
};

export default productService; 